package com.practice.controller;

import com.practice.service.MinioService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文件操作
 *
 * @author: kayn
 * 2024-11-01 17:15
 **/
@Slf4j
@RestController
@RequestMapping("/file")
public class MinioController {

    private final MinioService minioService;

    @Autowired
    public MinioController(MinioService minioService) {
        this.minioService = minioService;
    }

    /**
     * 文件上传
     * @param file 1
     * @return 1
     */
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 上传文件并返回文件的 URL
            return minioService.uploadFile(file);
        } catch (Exception e) {
            log.error("文件上传失败",e);
            return "文件上传失败: " + e.getMessage();
        }
    }

    /**
     * 获取文件 URL
     * @param fileName 1
     * @return 1
     */
    @GetMapping("/getFileUrl")
    public String getFileUrl(@RequestParam("fileName") String fileName) {
        try {
            return minioService.getFileUrl(fileName);
        } catch (Exception e) {
            log.error("获取文件 URL 失败",e);
            return "获取文件 URL 失败: " + e.getMessage();
        }
    }

    /**
     * 列出文件接口
     * @return 1
     */
    @GetMapping("/list")
    public List<String> listFiles() {
        try {
            return minioService.listFiles().stream()
                    .map(item -> item.objectName())
                    .toList();
        } catch (Exception e) {
            return List.of("获取文件列表失败: " + e.getMessage());
        }
    }
}
